package com.dji.compose_learning.utils

import android.app.Application
import androidx.activity.ComponentActivity
import androidx.annotation.PluralsRes
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

/**
 * Composable函数中获取viewModel封装
 */
@Composable
inline fun <reified VM : ViewModel> viewModel(): VM {
    return ViewModelProvider(LocalContext.current as ComponentActivity,
        ViewModelProvider.AndroidViewModelFactory(LocalContext.current.applicationContext as Application)).get(
        VM::class.java)
}

/**
 * Plurals获取封装
 */
@Composable
inline fun quantityResource(@PluralsRes id: Int, quantity: Int): String =
    LocalContext.current.resources.getQuantityString(id, quantity)

@Composable
fun <T> LiveData<T>.observeAsState(): State<T?> = observeAsState(value)

/**
 * livedata转state
 */
@Composable
fun <R, T : R> LiveData<T>.observeAsState(initial: R): State<R> {
    val lifecycleOwner = LocalLifecycleOwner.current
    val state = remember { mutableStateOf(initial) }
    DisposableEffect(this, lifecycleOwner) {
        val observer = Observer<T> { state.value = it }
        observe(lifecycleOwner, observer)
        onDispose { removeObserver(observer) }
    }
    return state
}